package com.google.project.client.Sharing;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Operator.OPTEntrypoint;
import com.google.project.client.ProjectManager.PMEditDailyReportDetail;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.Service.DailyReportDetailService;
import com.google.project.client.Service.DailyReportDetailServiceAsync;
import com.google.project.client.Service.DailyReportService;
import com.google.project.client.Service.DailyReportServiceAsync;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.MessageService;
import com.google.project.client.Service.MessageServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.UploadService;
import com.google.project.client.Service.UploadServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DailyReportDTO;
import com.google.project.shared.DailyReportDetailDTO;
import com.google.project.shared.DocumentDTO;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.UsersDTO;

public class DailyReportDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);

	@UiField
	Label lblReportForDate;
	@UiField
	Label lblProjectName;
	@UiField
	Label lblSenderName;
	@UiField
	Label lblCreatedOnDate;
	@UiField
	TextArea taReponse;
	@UiField(provided = true)
	CellTable<DailyReportDetailDTO> cbDailyReportDetail = new CellTable<DailyReportDetailDTO>();
	@UiField
	SimplePager pager;
	@UiField
	Button btnBack;
	@UiField
	VerticalPanel pWidget;
	@UiField
	Label lblAttach;
	@UiField
	HTMLPanel htmlPanel;
	@UiField Label lblDate;

	interface Binder extends UiBinder<Widget, DailyReportDetail> {
	}

	private final DailyReportDetailServiceAsync reportDetailService = GWT
			.create(DailyReportDetailService.class);

	private final DailyReportServiceAsync dailyReportService = GWT
			.create(DailyReportService.class);
	private final ProjectServiceAsync projectService = GWT
			.create(ProjectService.class);
	private final MessageServiceAsync messService = GWT
			.create(MessageService.class);
	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	final MultiSelectionModel<DailyReportDetailDTO> selectionModel = new MultiSelectionModel<DailyReportDetailDTO>();
	private UploadServiceAsync rpc = GWT.create(UploadService.class);

	DailyReportDTO currentDailyReport = new DailyReportDTO();
	MessageDTO messDTO = new MessageDTO();
	UsersDTO currentUserDTO = new UsersDTO();
	List<MessageDTO> listMessage = new ArrayList<MessageDTO>();

	public DailyReportDetail() {
		// initTableForOPT();
		initWidget(binder.createAndBindUi(this));
	}

	// contructor goi vao
	public DailyReportDetail(DailyReportDTO dailyReport) {

		initWidget(binder.createAndBindUi(this));
		this.currentDailyReport = dailyReport;
		getDailyReportDetail(dailyReport.getId());
		
		lblSenderName.setText(dailyReport.getFromUserName());
		lblCreatedOnDate.setText(CommonFuntion.convertToDate(new Date(
				dailyReport.getCreatedOnDate())));
		lblReportForDate.setText(CommonFuntion.convertToDate(new Date(
				dailyReport.getReportForDate())));
		getMessByParentID();
		getUrl(dailyReport.getId(), "3"); // get fileUpload
		// get info user from session
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(UsersDTO result) {
				currentUserDTO = result;
				initTableForOPT();
				// get name, id cua PM
				projectService.getProjectById(
						currentDailyReport.getProjectID(),
						new AsyncCallback<ProjectDTO>() {

							@Override
							public void onFailure(Throwable caught) {
							}

							@Override
							public void onSuccess(ProjectDTO result) {
								lblProjectName.setText(result.getProjectName());
								lblDate.setText("("+CommonFuntion.convertToDate(new Date(result.getStartDate()))+" - "+CommonFuntion.convertToDate(new Date(result.getDueDate()))+")");
								// opt phan hoi toi pm
								if (currentDailyReport.getFromUserID().equals(
										currentUserDTO.getUserId())) {
									messDTO.setSenderId(currentUserDTO
											.getUserId());
									messDTO.setSenderName(currentUserDTO
											.getUserName());
									messDTO.setReceiverId(result.getUserId());
									messDTO.setReceiverName(result
											.getAccountName());
								} else { // pm gui lai opt
									messDTO.setSenderId(result.getUserId());
									messDTO.setSenderName(result
											.getAccountName());
									messDTO.setReceiverId(currentUserDTO
											.getUserId());
									messDTO.setReceiverName(currentUserDTO
											.getUserName());
								}
							}
						});

			}

		});
	}

	// get url link file
	public void getUrl(String forID, String dataType) {
		rpc.getBlobs(forID, dataType, new AsyncCallback<List<DocumentDTO>>() {
			public void onSuccess(List<DocumentDTO> blobData) {
				if (blobData.size() > 0) {
					lblAttach.setVisible(true);
					htmlPanel.setVisible(true);
					String html = "<a target=\"_blank\" href="
							+ blobData.get(0).getUrl() + ">"
							+ blobData.get(0).getDocumentName() + "</a>";
					SafeHtml safeHtml = SafeHtmlUtils.fromSafeConstant(html);
					HTML na = new HTML(safeHtml);
					htmlPanel.add(na);
				}

			}

			public void onFailure(Throwable caught) {
				Window.alert("couldn't get blob list, rpc failed");
			}
		});
	}

	// getDailyReportDetail by DailyReportID
	private void getDailyReportDetail(String _dailyReportId) {
		reportDetailService.getDailyReportDetailByDaily(_dailyReportId,
				new AsyncCallback<List<DailyReportDetailDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(List<DailyReportDetailDTO> result) {
						LoadData(result);
					}
				});

	}

	// init table for OPT
	public void initTableForOPT() {
		// So thu tu
		TextColumn<DailyReportDetailDTO> indexColumn = new TextColumn<DailyReportDetailDTO>() {
			@Override
			public String getValue(DailyReportDetailDTO reportDetail) {
				return reportDetail.getIndex() + "";
			}
		};
		// task
		TextColumn<DailyReportDetailDTO> taskNameColumn = new TextColumn<DailyReportDetailDTO>() {
			@Override
			public String getValue(DailyReportDetailDTO reportDetail) {
				return reportDetail.getTaskName();
			}
		};
		// worktofinished
		TextColumn<DailyReportDetailDTO> workToFinishedColumn = new TextColumn<DailyReportDetailDTO>() {
			@Override
			public String getValue(DailyReportDetailDTO reportDetail) {
				return reportDetail.getWorkToFinished().toString() + "("
						+ reportDetail.getUnit() + ")";
			}
		};
		TextColumn<DailyReportDetailDTO> contentColumn = new TextColumn<DailyReportDetailDTO>() {
			@Override
			public String getValue(DailyReportDetailDTO reportDetail) {
				return reportDetail.getContent();
			}
		};
		taskNameColumn.setCellStyleNames("celltable");
		cbDailyReportDetail.addColumn(indexColumn, "STT");
		cbDailyReportDetail.addColumn(taskNameColumn, "Công việc");
		cbDailyReportDetail.addColumn(workToFinishedColumn,
				"Khối lượng hoàn thành");
		cbDailyReportDetail.addColumn(contentColumn, "Nội dung");
		cbDailyReportDetail.setStyleName("ttable");
		cbDailyReportDetail.setWidth("100%", true);

	}

	// init table for PM
//	public void initTableForPM() {
//		// So thu tu
//		TextColumn<DailyReportDetailDTO> indexColumn = new TextColumn<DailyReportDetailDTO>() {
//			@Override
//			public String getValue(DailyReportDetailDTO reportDetail) {
//				return reportDetail.getIndex() + "";
//			}
//		};
//		cbDailyReportDetail.setSelectionModel(selectionModel,
//				DefaultSelectionEventManager
//						.<DailyReportDetailDTO> createCheckboxManager());
//		Column<DailyReportDetailDTO, Boolean> checkColumn = new Column<DailyReportDetailDTO, Boolean>(
//				new CheckboxCell(true, false)) {
//			@Override
//			public Boolean getValue(DailyReportDetailDTO object) {
//				// Get the value from the selection model.
//				return selectionModel.isSelected(object);
//			}
//		};
//		cbDailyReportDetail.addColumn(checkColumn, SafeHtmlUtils
//				.fromSafeConstant("<br/>"));
//		cbDailyReportDetail.setColumnWidth(checkColumn, 40, Unit.PX);
//
//		// task
//		TextColumn<DailyReportDetailDTO> taskNameColumn = new TextColumn<DailyReportDetailDTO>() {
//			@Override
//			public String getValue(DailyReportDetailDTO reportDetail) {
//				return reportDetail.getTaskName();
//			}
//		};
//		// worktofinished
//		TextColumn<DailyReportDetailDTO> workToFinishedColumn = new TextColumn<DailyReportDetailDTO>() {
//			@Override
//			public String getValue(DailyReportDetailDTO reportDetail) {
//				return reportDetail.getWorkToFinished().toString() + "("
//						+ reportDetail.getUnit() + ")";
//			}
//		};
//		TextColumn<DailyReportDetailDTO> contentColumn = new TextColumn<DailyReportDetailDTO>() {
//			@Override
//			public String getValue(DailyReportDetailDTO reportDetail) {
//				return reportDetail.getContent();
//			}
//		};
//		taskNameColumn.setCellStyleNames("celltable");
//		cbDailyReportDetail.addColumn(indexColumn, "STT");
//		cbDailyReportDetail.addColumn(taskNameColumn, "Công việc");
//		cbDailyReportDetail.addColumn(workToFinishedColumn,
//				"Khối lượng hoàn thành");
//		cbDailyReportDetail.addColumn(contentColumn, "Nội dung");
//		cbDailyReportDetail.setStyleName("ttable");
//		cbDailyReportDetail.setWidth("100%", true);
//
//	}

	// load data fill to celltable
	protected void LoadData(List<DailyReportDetailDTO> dailyReportList) {
		ListDataProvider<DailyReportDetailDTO> dataProvider = new ListDataProvider<DailyReportDetailDTO>();
		// Connect the table to the data provider.
		dataProvider.addDataDisplay(cbDailyReportDetail);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index = 1;
		List<DailyReportDetailDTO> list = dataProvider.getList();
		for (DailyReportDetailDTO dailyDetail : dailyReportList) {
			dailyDetail.setIndex(index);
			list.add(dailyDetail);
			index++;
		}
		// SimplePager
		pager.setDisplay(cbDailyReportDetail);
		pager.setPageSize(4);
	}

	// get all Message by ParentID= id của báo cáo cha
	public void getMessByParentID() {
		messService.getMessageList(new AsyncCallback<List<MessageDTO>>() {

			@Override
			public void onSuccess(List<MessageDTO> result) {
				try {
					for (MessageDTO messageDTO : result) {
						listMessage.add(messageDTO);
					}

					List<MessageDTO> tempMess = new ArrayList<MessageDTO>();
					for (MessageDTO mess : listMessage) {
						if (mess.getParentId()!=null && mess.getParentId().equals(
								currentDailyReport.getId())) {
							tempMess.add(mess);
						}
					}
					String top = "<div class=\"container3\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					String top2 = "<div class=\"container2\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom2 = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					if (tempMess != null && tempMess.size() > 0) {
						int r = tempMess.size();
						int c = 1;
						Grid grid = new Grid(r, c);
						pWidget.add(grid);
						for (int i = 0; i < tempMess.size(); i++) {
							String senderName = tempMess.get(i).getSenderName();
							String content = tempMess.get(i).getContent();
							String createdOnDate = CommonFuntion
									.convertToDate(new Date(tempMess.get(i)
											.getCreatedOnDate()));
							grid.setWidget(i, 0, new HTML(top + "Người Gửi: "
									+ senderName + " <br> Ngày Gửi: "
									+ createdOnDate + "<br><br>" + top2
									+ content + bottom2 + bottom + "<br>"));
						}

					}

					Scheduler.get().scheduleDeferred(
							new Scheduler.ScheduledCommand() {
								public void execute() {
									
								}
							});

				} catch (Exception ex) {
					ex.getMessage();
				}
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}

	// gui phan hoi
	@UiHandler("btnReponse")
	void onBtnReponseClick(ClickEvent event) {
		messDTO.setContent(taReponse.getText());
		messDTO.setCreatedOnDate(new Date().getTime());
		messDTO.setParentId(currentDailyReport.getId());
		messDTO.setProjectId(currentDailyReport.getProjectID());
		messDTO.setTypeId(2);
		messService.sendMessage(messDTO, new AsyncCallback<MessageDTO>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(MessageDTO result) {
				// set lai status cua report cha
				if (currentDailyReport.getFromUserID().equals(
						currentUserDTO.getUserId())) {
					dailyReportService.updateStatusDailyReport(
							currentDailyReport.getId(), 1,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {

								}

								@Override
								public void onSuccess(Void result) {
									if(listMessage.size()>0){
										pWidget.clear();
										listMessage.clear();
										}
									getMessByParentID();
									taReponse.setText("");
									Window.alert("Gửi phản hồi thành công!");
								}
							});
				} else {
					dailyReportService.updateStatusDailyReport(
							currentDailyReport.getId(), 2,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {

								}

								@Override
								public void onSuccess(Void result) {
									if(listMessage.size()>0){
										pWidget.clear();
										listMessage.clear();
										}
									getMessByParentID();
									taReponse.setText("");
									Window.alert("Gửi phản hồi thành công!");
								}
							});
				}

			}
		});
	}

	@UiHandler("btnBack")
	void onBtnBack2Click(ClickEvent event) {
		if (currentUserDTO.getUserGroup() == 3) {
			OPTEntrypoint.get().OPTDailyReportList();
		}
		if (currentUserDTO.getUserGroup() == 2) {
			PMEntrypoint.get().PMDailyReportList();
		}
	}
}
